<?php

/**
 * FrontPress user class
 */
class FP_User extends FP_Thing {
	static $__table = 'users';
	static $__has_meta = true;
	static $__meta_table = 'usermeta';

	var $ID;
	var $user_login;
	var $user_pass;
	var $user_nicename;
	var $user_email;
	var $user_url;
	var $user_registered;
	var $user_status;
	var $display_name;

	private static function _init_auth() {
		global $wp_users_object, $wp_auth;
		if ( !isset( $wp_users_object ) ) {
			/**
			 * @var WP_Users
			 * @global WP_Users $wp_users_object
			 */
			$wp_users_object = new WP_Users( FP_Thing::$db );

			add_action( 'WP_Users::_put_user', array( 'FP_User', '_cache_flush' ) );
		}
		if ( !isset( $wp_auth ) ) {
			$cookies = array();

			$cookies['logged_in'][] = array(
				'domain' => false,
				'path' => false,
				'name' => md5( frontpress_uri() ) . '_logged_in'
			);

			$cookies['auth'][] = array(
				'domain' => false,
				'path' => false,
				'name' => md5( frontpress_uri() ) . '_auth'
			);

			$cookies['secure_auth'][] = array(
				'domain' => false,
				'path' => false,
				'name' => md5( frontpress_uri() ) . '_secure_auth',
				'secure' => true
			);

			/**
			 * @var WP_Auth
			 * @global WP_Auth $wp_auth
			 */
			$wp_auth = new WP_Auth( FP_Thing::$db, $wp_users_object, $cookies );
		}
	}

	/**
	 * @access private
	 * @param array $user
	 */
	static function _cache_flush( $user ) {
		wp_cache_delete( $user['ID'], 'FP_User' );
		wp_cache_flush( 'FP_User__query' );
	}

	/**
	 * @access private
	 * @param FP_User $user
	 */
	static function _after_save( $user ) {
		global $wp_users_object;
		static::_init_auth();
		wp_cache_delete( $user->ID, 'users' );
		$wp_users_object->get_user( $user->ID, array( 'from_cache' => false ) );
	}

	/**
	 * @return FP_User
	 */
	static function current() {
		global $wp_auth;
		static::_init_auth();

		if ( ( $curr_user = $wp_auth->get_current_user() ) && $curr_user->ID ) {
			return new FP_User( $curr_user, true );
		}
		return null;
	}

	/**
	 * @return bool
	 */
	static function logged_in() {
		return !!static::current();
	}

	function set_as_current() {
		global $wp_auth;
		static::_init_auth();

		$wp_auth->set_current_user( $this->ID );
		$wp_auth->set_auth_cookie( $this->ID );
		$wp_auth->set_auth_cookie( $this->ID, 0, 0, 'logged_in' );
	}

	static function by_id( $id ) {
		return static::__callStatic( 'by_ID', array( $id ) );
	}

	/**
	 * @return bool
	 */
	function can() {
		if ( isset( $this ) && isset( $this->ID ) ) {
			$id = $this->ID;
		} else {
			$id = FP_User::current()->ID;
		}
		if ( !$id )
			return false;

		$user = new BP_User( $id );
		return call_user_func_array( array( &$user, 'has_cap' ), func_get_args() );
	}
}

add_action( 'FP_User_after_save', array( 'FP_User', '_after_save' ) );
add_action( 'FP_User_meta_set', array( 'FP_User', '_after_save' ) );
add_action( 'FP_User_meta_delete', array( 'FP_User', '_after_save' ) );